package com.pay.game.central.web.service;

import com.pay.game.central.web.bean.HistoryOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Service
public class HistoryOrderService {

    @Autowired
    private DirectoryService directoryService;

    private Map<String, CopyOnWriteArraySet<HistoryOrder>> map = new ConcurrentHashMap<>();

    /**
     * 添加 订单到缓存
     * @param storeId
     * @param orderTag
     * @param timestamp
     */
    public synchronized  void putNewOrder(String storeId, String orderTag, int timestamp){
        CopyOnWriteArraySet<HistoryOrder> set = map.get(storeId);
        if (set == null) {
            set = new CopyOnWriteArraySet<>();
        }
        set.add(new HistoryOrder(orderTag, timestamp));
        map.put(storeId, set);
    }

    /**
     * 从缓存移除订单
     * @param orderTag 要移除的订单tag
     */
    public synchronized void removeOldOrder(String orderTag) {
        HistoryOrder order = null;
        for (Map.Entry<String, CopyOnWriteArraySet<HistoryOrder>> entry: map.entrySet()) {
            for (HistoryOrder ho: entry.getValue()) {
                if (ho.getTag().equals(orderTag)){
                    order = ho;
                    break;
                }
            }
            if (order != null){
                entry.getValue().remove(order);
                break;
            }
        }
    }

    /**
     * 从缓存移除订单
     * @param timestamp 当前时间截
     */
    public synchronized void removeOldOrder(int timestamp) {
        int orderTimeout = directoryService.getOrderTimeout();
        for (Map.Entry<String, CopyOnWriteArraySet<HistoryOrder>> entry: map.entrySet()) {
            List<HistoryOrder> needRemove = new ArrayList<>();
            for (HistoryOrder ho: entry.getValue()) {
                if (timestamp - ho.getTimestamp() >= orderTimeout){
                    needRemove.add(ho);
                }
            }
            if (!needRemove.isEmpty()){
                entry.getValue().removeAll(needRemove);
                break;
            }
        }
    }

    public synchronized  Map<String,Integer> lockOrderSize() {
        Map<String,Integer>  rlt = new HashMap<>();
        for (Map.Entry<String, CopyOnWriteArraySet<HistoryOrder>> entry: map.entrySet()) {
            rlt.put(entry.getKey(), entry.getValue().size());
        }
        return rlt;
    }


    @Scheduled(fixedRate = 5000)
    public void removeOrderByTime(){
        removeOldOrder((int) (System.currentTimeMillis() / 1000));
    }

}
